// 时间戳转换工具
class TimestampConverter {
    /**
     * 获取当前时间戳
     * @param {string} unit - 时间戳单位 ('seconds' | 'milliseconds')
     * @returns {Object} - 处理结果
     */
    static getCurrentTimestamp(unit = 'seconds') {
        try {
            const now = Date.now();
            const timestamp = unit === 'seconds' ? Math.floor(now / 1000) : now;
            
            return {
                success: true,
                data: {
                    timestamp: timestamp,
                    unit: unit,
                    date: new Date(now)
                }
            };
        } catch (error) {
            return { success: false, error: '获取当前时间戳失败: ' + error.message };
        }
    }

    /**
     * 时间戳转日期时间
     * @param {string|number} timestamp - 时间戳
     * @param {Object} options - 转换选项
     * @returns {Object} - 处理结果
     */
    static timestampToDate(timestamp, options = {}) {
        try {
            if (!timestamp && timestamp !== 0) {
                return { success: false, error: '请输入时间戳' };
            }

            const {
                unit = 'auto',
                timezone = 'local',
                format = 'full'
            } = options;

            // 清理输入
            let cleanTimestamp = String(timestamp).trim();
            
            // 移除非数字字符
            cleanTimestamp = cleanTimestamp.replace(/[^\d.-]/g, '');
            
            if (!cleanTimestamp) {
                return { success: false, error: '时间戳格式不正确' };
            }

            let numTimestamp = parseFloat(cleanTimestamp);
            
            if (isNaN(numTimestamp)) {
                return { success: false, error: '时间戳必须是数字' };
            }

            // 自动检测时间戳单位
            let detectedUnit = unit;
            if (unit === 'auto') {
                // 10位数字判断为秒，13位及以上判断为毫秒
                detectedUnit = String(Math.abs(Math.floor(numTimestamp))).length <= 10 ? 'seconds' : 'milliseconds';
            }

            // 转换为毫秒
            let msTimestamp = detectedUnit === 'seconds' ? numTimestamp * 1000 : numTimestamp;
            
            // 验证时间戳合理性（1970-2100年之间）
            const minTimestamp = new Date('1970-01-01').getTime();
            const maxTimestamp = new Date('2100-01-01').getTime();
            
            if (msTimestamp < minTimestamp || msTimestamp > maxTimestamp) {
                return { 
                    success: false, 
                    error: `时间戳超出合理范围 (1970-2100年)，当前解析为: ${new Date(msTimestamp).toISOString()}` 
                };
            }

            const date = new Date(msTimestamp);
            
            if (isNaN(date.getTime())) {
                return { success: false, error: '无效的时间戳' };
            }

            // 生成多种格式
            const results = this.formatDate(date, timezone);
            
            return {
                success: true,
                data: {
                    timestamp: numTimestamp,
                    detectedUnit: detectedUnit,
                    date: date,
                    formats: results,
                    timezone: timezone
                }
            };
        } catch (error) {
            return { success: false, error: '时间戳转换失败: ' + error.message };
        }
    }

    /**
     * 日期时间转时间戳
     * @param {string} dateString - 日期时间字符串
     * @param {Object} options - 转换选项
     * @returns {Object} - 处理结果
     */
    static dateToTimestamp(dateString, options = {}) {
        try {
            if (!dateString || !dateString.trim()) {
                return { success: false, error: '请输入日期时间' };
            }

            const {
                unit = 'seconds',
                timezone = 'local'
            } = options;

            let date;
            const cleanDateString = dateString.trim();

            // 尝试多种日期格式解析
            const parseAttempts = [
                // 直接解析
                () => new Date(cleanDateString),
                // ISO格式
                () => new Date(cleanDateString + 'T00:00:00'),
                // 中文格式处理
                () => {
                    const chinesePattern = /(\d{4})[年\-\/](\d{1,2})[月\-\/](\d{1,2})日?\s*(\d{1,2})?[时:]?(\d{1,2})?[分:]?(\d{1,2})?秒?/;
                    const match = cleanDateString.match(chinesePattern);
                    if (match) {
                        const [, year, month, day, hour = '0', minute = '0', second = '0'] = match;
                        return new Date(year, month - 1, day, hour, minute, second);
                    }
                    return null;
                },
                // 常见格式
                () => {
                    const formats = [
                        /^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/,
                        /^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/,
                        /^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})$/,
                        /^(\d{4})-(\d{1,2})-(\d{1,2})$/,
                        /^(\d{4})\/(\d{1,2})\/(\d{1,2})$/
                    ];
                    
                    for (const format of formats) {
                        const match = cleanDateString.match(format);
                        if (match) {
                            if (match.length === 4) { // 只有日期
                                return new Date(match[1], match[2] - 1, match[3]);
                            } else if (match.length === 7) { // 日期+时间
                                if (match[1].length === 4) { // YYYY-MM-DD格式
                                    return new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
                                } else { // MM/DD/YYYY格式
                                    return new Date(match[3], match[1] - 1, match[2], match[4], match[5], match[6]);
                                }
                            }
                        }
                    }
                    return null;
                }
            ];

            // 尝试解析
            for (const attempt of parseAttempts) {
                try {
                    const result = attempt();
                    if (result && !isNaN(result.getTime())) {
                        date = result;
                        break;
                    }
                } catch (e) {
                    continue;
                }
            }

            if (!date || isNaN(date.getTime())) {
                return { 
                    success: false, 
                    error: '无法解析日期格式，支持格式：YYYY-MM-DD、YYYY/MM/DD、MM/DD/YYYY、YYYY年MM月DD日等' 
                };
            }

            // 验证日期合理性
            const minDate = new Date('1970-01-01');
            const maxDate = new Date('2100-01-01');
            
            if (date < minDate || date > maxDate) {
                return { 
                    success: false, 
                    error: `日期超出合理范围 (1970-2100年)，当前解析为: ${date.toISOString()}` 
                };
            }

            const timestamp = date.getTime();
            const result = unit === 'seconds' ? Math.floor(timestamp / 1000) : timestamp;

            return {
                success: true,
                data: {
                    dateString: cleanDateString,
                    date: date,
                    timestamp: result,
                    unit: unit,
                    formats: this.formatDate(date, timezone)
                }
            };
        } catch (error) {
            return { success: false, error: '日期转换失败: ' + error.message };
        }
    }

    /**
     * 批量转换时间戳
     * @param {string} timestamps - 时间戳列表（每行一个）
     * @param {Object} options - 转换选项
     * @returns {Object} - 处理结果
     */
    static batchConvert(timestamps, options = {}) {
        try {
            if (!timestamps || !timestamps.trim()) {
                return { success: false, error: '请输入时间戳列表' };
            }

            const lines = timestamps.split('\n').map(line => line.trim()).filter(line => line);
            
            if (lines.length === 0) {
                return { success: false, error: '没有有效的时间戳' };
            }

            const results = [];
            let successCount = 0;
            let errorCount = 0;

            for (let i = 0; i < lines.length; i++) {
                const line = lines[i];
                const result = this.timestampToDate(line, options);
                
                results.push({
                    line: i + 1,
                    input: line,
                    success: result.success,
                    data: result.success ? result.data : null,
                    error: result.success ? null : result.error
                });

                if (result.success) {
                    successCount++;
                } else {
                    errorCount++;
                }
            }

            return {
                success: true,
                data: {
                    results: results,
                    summary: {
                        total: lines.length,
                        success: successCount,
                        error: errorCount
                    }
                }
            };
        } catch (error) {
            return { success: false, error: '批量转换失败: ' + error.message };
        }
    }

    /**
     * 格式化日期为多种格式
     * @param {Date} date - 日期对象
     * @param {string} timezone - 时区
     * @returns {Object} - 各种格式的日期字符串
     */
    static formatDate(date, timezone = 'local') {
        try {
            const pad = (num) => String(num).padStart(2, '0');
            
            // 基础信息
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hour = date.getHours();
            const minute = date.getMinutes();
            const second = date.getSeconds();
            const ms = date.getMilliseconds();

            // 星期
            const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            const weekdaysEn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            
            // 月份
            const monthsEn = ['January', 'February', 'March', 'April', 'May', 'June',
                             'July', 'August', 'September', 'October', 'November', 'December'];

            return {
                // 标准格式
                iso: date.toISOString(),
                utc: date.toUTCString(),
                local: date.toLocaleString('zh-CN'),
                
                // 自定义格式
                'YYYY-MM-DD HH:mm:ss': `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`,
                'YYYY/MM/DD HH:mm:ss': `${year}/${pad(month)}/${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`,
                'MM/DD/YYYY HH:mm:ss': `${pad(month)}/${pad(day)}/${year} ${pad(hour)}:${pad(minute)}:${pad(second)}`,
                'DD/MM/YYYY HH:mm:ss': `${pad(day)}/${pad(month)}/${year} ${pad(hour)}:${pad(minute)}:${pad(second)}`,
                
                // 仅日期
                'YYYY-MM-DD': `${year}-${pad(month)}-${pad(day)}`,
                'YYYY/MM/DD': `${year}/${pad(month)}/${pad(day)}`,
                'MM/DD/YYYY': `${pad(month)}/${pad(day)}/${year}`,
                'DD/MM/YYYY': `${pad(day)}/${pad(month)}/${year}`,
                
                // 仅时间
                'HH:mm:ss': `${pad(hour)}:${pad(minute)}:${pad(second)}`,
                'HH:mm': `${pad(hour)}:${pad(minute)}`,
                
                // 中文格式
                chinese: `${year}年${month}月${day}日 ${pad(hour)}时${pad(minute)}分${pad(second)}秒`,
                chineseDate: `${year}年${month}月${day}日`,
                chineseTime: `${pad(hour)}时${pad(minute)}分${pad(second)}秒`,
                
                // 英文格式
                english: `${monthsEn[month - 1]} ${day}, ${year} ${pad(hour)}:${pad(minute)}:${pad(second)}`,
                
                // 相对时间
                relative: this.getRelativeTime(date),
                
                // 星期
                weekday: weekdays[date.getDay()],
                weekdayEn: weekdaysEn[date.getDay()],
                
                // 详细信息
                details: {
                    year: year,
                    month: month,
                    day: day,
                    hour: hour,
                    minute: minute,
                    second: second,
                    millisecond: ms,
                    weekday: date.getDay(),
                    dayOfYear: this.getDayOfYear(date),
                    weekOfYear: this.getWeekOfYear(date),
                    quarter: Math.ceil(month / 3),
                    isLeapYear: this.isLeapYear(year)
                }
            };
        } catch (error) {
            return { error: '格式化失败: ' + error.message };
        }
    }

    /**
     * 获取相对时间
     * @param {Date} date - 日期对象
     * @returns {string} - 相对时间字符串
     */
    static getRelativeTime(date) {
        const now = new Date();
        const diff = now.getTime() - date.getTime();
        const absDiff = Math.abs(diff);
        
        const second = 1000;
        const minute = second * 60;
        const hour = minute * 60;
        const day = hour * 24;
        const month = day * 30;
        const year = day * 365;
        
        const isPast = diff > 0;
        const suffix = isPast ? '前' : '后';
        
        if (absDiff < minute) {
            return `${Math.floor(absDiff / second)}秒${suffix}`;
        } else if (absDiff < hour) {
            return `${Math.floor(absDiff / minute)}分钟${suffix}`;
        } else if (absDiff < day) {
            return `${Math.floor(absDiff / hour)}小时${suffix}`;
        } else if (absDiff < month) {
            return `${Math.floor(absDiff / day)}天${suffix}`;
        } else if (absDiff < year) {
            return `${Math.floor(absDiff / month)}个月${suffix}`;
        } else {
            return `${Math.floor(absDiff / year)}年${suffix}`;
        }
    }

    /**
     * 获取一年中的第几天
     * @param {Date} date - 日期对象
     * @returns {number} - 天数
     */
    static getDayOfYear(date) {
        const start = new Date(date.getFullYear(), 0, 1);
        return Math.floor((date - start) / (24 * 60 * 60 * 1000)) + 1;
    }

    /**
     * 获取一年中的第几周
     * @param {Date} date - 日期对象
     * @returns {number} - 周数
     */
    static getWeekOfYear(date) {
        const firstDay = new Date(date.getFullYear(), 0, 1);
        const dayOfYear = this.getDayOfYear(date);
        return Math.ceil((dayOfYear + firstDay.getDay()) / 7);
    }

    /**
     * 判断是否为闰年
     * @param {number} year - 年份
     * @returns {boolean} - 是否为闰年
     */
    static isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
    }

    /**
     * 时区转换
     * @param {Date} date - 日期对象
     * @param {string} targetTimezone - 目标时区
     * @returns {Object} - 转换结果
     */
    static convertTimezone(date, targetTimezone) {
        try {
            if (!date) {
                return { success: false, error: '日期不能为空' };
            }

            const timezones = {
                'UTC': 0,
                'GMT': 0,
                'EST': -5,
                'PST': -8,
                'CST': -6,
                'MST': -7,
                'JST': 9,
                'CST_CHINA': 8,
                'IST': 5.5,
                'CET': 1,
                'AEST': 10
            };

            const offset = timezones[targetTimezone];
            if (offset === undefined) {
                return { success: false, error: '不支持的时区' };
            }

            const utcTime = date.getTime() + (date.getTimezoneOffset() * 60000);
            const targetTime = new Date(utcTime + (offset * 3600000));

            return {
                success: true,
                data: {
                    original: date,
                    converted: targetTime,
                    timezone: targetTimezone,
                    offset: offset,
                    formats: this.formatDate(targetTime)
                }
            };
        } catch (error) {
            return { success: false, error: '时区转换失败: ' + error.message };
        }
    }
}